//  购物车数据存储
import { ref, computed } from 'vue'

const cartItems = ref([])

export const useCartStore = () => {
  // 添加商品到购物车
  const addToCart = (product) => {
    const existingItem = cartItems.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity++
    } else {
      cartItems.value.push({
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: 1,
        image: product.image,
        selected: false
      })
    }
  }

  // 从购物车移除商品
  const removeFromCart = (productId) => {
    const index = cartItems.value.findIndex(item => item.id === productId)
    if (index > -1) {
      cartItems.value.splice(index, 1)
    }
  }

  // 更新商品数量
  const updateQuantity = (productId, quantity) => {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      item.quantity = quantity
    }
  }

  // 获取购物车商品列表
  const getCartItems = computed(() => cartItems.value)

  // 获取购物车商品总数
  const getCartTotal = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0)
  })

  // 获取购物车总价
  const getCartPrice = computed(() => {
    return cartItems.value.reduce((total, item) => {
      return item.selected ? total + (item.price * item.quantity) : total
    }, 0)
  })

  return {
    cartItems,
    addToCart,
    removeFromCart,
    updateQuantity,
    getCartItems,
    getCartTotal,
    getCartPrice
  }
} 